package org.lg.example;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.lg.entity.Student;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * jackson 示例
 * @author LG
 */
public class TestJson {
    public static void main(String[] args) throws IOException {
        String jsonString1 = "[{\"sno\":\"0001\",\"sex\":\"张三\"},{\"sno\":\"0002\",\"sex\":\"李四\"}] ";
        Student student = new Student("0005", "男");
        Student student2 = new Student("0006", "女");
        ObjectMapper objectMapper = new ObjectMapper();
        //声明数组转换为List
        List<Student> students = Arrays.asList(new Student[]{student, student2});
        String string = objectMapper.writeValueAsString(student);//转换单个对象为json字符串
        System.out.println(string);
        String string1 = objectMapper.writeValueAsString(students);//转换集合对象为json字符串
        System.out.println(string1);

//json字符串转为单个java对象
        String studentStr = "{\"sno\":\"0001\",\"sex\":\"男\"}";
        Student student1 = objectMapper.readValue(studentStr, Student.class);
        System.out.println(student1);
        //json字符串转换为java集合对象,集合对象需要用类型引用 TypeReferen包装
        List<Student> list = objectMapper.readValue(jsonString1, new TypeReference<List<Student>>(){});
        list.forEach(System.out::println);
    }
}
